﻿using Enum;
using MediatR;
using Practice.API.Application.Commands.Roles;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.UserW
{
    public class UserListHandler : IRequestHandler<UserListCommand, Result>
    {
        public readonly IBaseRepository<Users> UsersRepository;
        public readonly IBaseRepository<UserRole> UserRoleRepository;
        public readonly IBaseRepository<Role> RoleRepository;

        public UserListHandler(IBaseRepository<Users> usersRepository, IBaseRepository<UserRole> userRoleRepository, IBaseRepository<Role> roleRepository)
        {
            UsersRepository = usersRepository;
            UserRoleRepository = userRoleRepository;
            RoleRepository = roleRepository;
        }

        public async Task<Result> Handle(UserListCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.Success };
            try
            {
                var list = (from a in UsersRepository.GetAll()
                            join b in UserRoleRepository.GetAll() on a.UserId equals b.UserId
                            join c in RoleRepository.GetAll() on b.RoleId equals c.RoleId
                            where a.UserStatus==false
                            group c by new { a.UserName, a.Pwd, a.UserStatus, b.CreateTime,a.UserId } into g
                            select new RoleListDto()
                            {
                                UserName = g.Key.UserName,
                                Pwd = g.Key.Pwd,
                                Userid=g.Key.UserId,
                                UserStatus = g.Key.UserStatus,
                                RoleName = string.Join(',', g.Select(x => x.RoleName)),
                                CreateTime = g.Key.CreateTime
                            }).ToList();
                if (request.UserName != "")
                {
                    list = list.Where(x => x.UserName.Contains(request.UserName)).ToList();
                }

                result.Data = list;
                result.Code = (int)CommonEnumCode.Success;



            }
            catch (Exception)
            {

                result.Msg = "显示查询失败";

            }
            return result;
        }
    }
    public class RoleListDto
    {
        public string UserName { get; set; }
        public string Pwd { get; set; }
        public int Userid { get; set; }
        public bool UserStatus { get; set; }
        public string RoleName { get; set; }
        public string CreateTime { get; set; } = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
    }
}
